package com.hand.wfive.loginAndVip.ui

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.view.View
import android.webkit.*
import com.hand.wfive.R
import com.hand.wfive.base.BaseActivity
import com.hand.wfive.entity.Params
import com.hand.wfive.util.click.singleClick
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView
import kotlinx.android.synthetic.main.login_activity_h5_pay.*

@SuppressLint("all")
class H5PayActivity : BaseActivity() {

    companion object {
        @JvmStatic
        fun showIntent(context: Context?, orderUrl: String, payType: String): Intent {
            val intent = Intent(context, H5PayActivity::class.java)
            intent.putExtra(Params.payType, payType)
            intent.putExtra(Params.orderUrl, orderUrl)
            return intent
        }
    }

    private var mShowTip = false
    private var mPayType = "wxpay"

    private var mPauseTime = 0L

    override fun getContentViewId() = R.layout.login_activity_h5_pay

    override fun init() {
        val orderUrl = intent.getStringExtra(Params.orderUrl)
        if (orderUrl.isNullOrEmpty()) {
            finish()
            return
        }
        mPayType = intent.getStringExtra(Params.payType) ?: mPayType

        topBar.setTitle("确认订单")
        topBar.addLeftBackImageButton().singleClick { finish() }

        webView.settings.javaScriptEnabled = true
        webView.settings.defaultTextEncodingName = "UTF-8"
        webView.settings.javaScriptCanOpenWindowsAutomatically = true
        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress == 100) hideLoading()
            }
        }
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView?, request: WebResourceRequest
            ): Boolean {
                val url = request.url.toString()
                if (mPayType == "wxpay") {
                    if (url.startsWith("weixin://")) {
                        wechatPay(url)
                    } else {
                        val extraHeaders = HashMap<String, String>()
                        extraHeaders["Referer"] = "https://www.quexingnet.cn/"
                        webView.loadUrl(url, extraHeaders)
                    }
                } else {
                    if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                        aliPay(url)
                        return true
                    }
                    // ------- 处理结束 -------
                    if (!(url.startsWith("http") || url.startsWith("https"))) {
                        return true
                    }
                    webView.loadUrl(url)
                }
                return true
            }

            override fun onReceivedSslError(
                view: WebView?, handler: SslErrorHandler?, error: SslError?
            ) {
                handler?.proceed()
            }
        }

        showLoading()
        println("orderUrl=$orderUrl")
        webView.loadUrl(orderUrl)
    }

    private fun wechatPay(url: String) {
        try {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.data = Uri.parse(url)
            mContext.startActivity(intent)
            mShowTip = true
        } catch (e: Exception) {
            e.printStackTrace()
            showErrorTip(topBar,"请先安装微信，再发起支付")
        }
    }

    private fun aliPay(url: String) {
        try {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.data = Uri.parse(url)
            mContext.startActivity(intent)
            mShowTip = true
            setResult(RESULT_OK)
        } catch (e: Exception) {
            e.printStackTrace()
            showErrorTip(topBar,"请先安装支付宝，再发起支付")
        }
    }

    override fun onPause() {
        super.onPause()
        println("onPause")
        mPauseTime = System.currentTimeMillis()
    }

    override fun onResume() {
        super.onResume()
        println("onResume")
        if (System.currentTimeMillis() - mPauseTime < 1) {
            return
        }
        if (mShowTip) {
            mShowTip = false
            showTip()
        }
    }

    private fun showTip() {
        val dialog = Dialog(mContext, R.style.CustomDialog)
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(false)
        dialog.setContentView(R.layout.login_dialog_h5_pay_result)
        val listener = View.OnClickListener {
            dialog.dismiss()
            setResult(RESULT_OK)
            finish()
        }
        dialog.findViewById<QMUIAlphaTextView>(R.id.qtv_unpaid).singleClick(listener)
        dialog.findViewById<QMUIAlphaTextView>(R.id.qtv_paid).singleClick(listener)
        dialog.show()
    }
}